<template>
  <div class='container question-new'>
    <el-card>
      <div slot="header">{{$route.query.id?'试题修改':'试题录入'}}</div>
      <!-- 表单组件 -->
      <el-form label-width="120px"
               class="demo-ruleForm"
               ref="form"
               :model="qsForm"
               :rules="rules">
        <!-- 学科 -->
        <el-form-item label="学科:"
                      prop="subjectID">
          <el-select style="width:400px"
                     v-model="qsForm.subjectID"
                     @change="changeSubject">
            <el-option v-for="item in subjectOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录:"
                      prop="catalogID">
          <el-select v-model="qsForm.catalogID"
                     style="width:400px">
            <el-option v-for="item in catalogOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业:"
                      prop="enterpriseID">
          <el-select v-model="qsForm.enterpriseID"
                     style="width:400px">
            <el-option v-for="item in enterpriseOptions"
                       :key="item.id"
                       :label="item.company"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市:"
                      prop="city">
          <el-select v-model="qsForm.province"
                     @change="getArea"
                     style="width:198px">
            <el-option v-for="item in cityOptions"
                       :key="item"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
          <el-select v-model="qsForm.city"
                     style="width:198px;margin-left:4px">
            <el-option v-for="item in areaOptions"
                       :key="item"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向:"
                      prop="direction">
          <el-select v-model="qsForm.direction"
                     style="width:400px">
            <el-option v-for="item in directionOptions"
                       :key="item"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型:"
                      prop="questionType">
          <template>
            <el-radio-group @change="changeRadio({})"
                            v-model="qsForm.questionType">
              <el-radio v-for="item in questionType"
                        :key="item.value"
                        :label="item.value+''">{{item.label}}</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度:"
                      prop="difficulty">
          <el-radio-group v-model="qsForm.difficulty">
            <el-radio v-for="item in difficulty"
                      :key="item.value"
                      :label="item.value+''">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干:"
                      prop="question">
          <!-- 富文本需要失去焦点时触发校验 -->
          <quill-editor @blur="checkQustion"
                        v-model="qsForm.question"
                        :options="editorOptions">
          </quill-editor>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项:"
                      prop="options"
                      v-if="qsForm.questionType!=='3'">
          <div class="option_item"
               v-for="item in qsForm.options"
               :key="item.code">
            <!-- 单选 -->
            <el-radio v-if="qsForm.questionType==='1'"
                      @change="changeRadio(item)"
                      v-model="item.isRight"
                      style="margin-right:0"
                      :label="true">{{item.code}}:</el-radio>
            <!-- 多选 -->
            <el-checkbox v-if="qsForm.questionType==='2'"
                         v-model="item.isRight"
                         :label="true">{{item.code}}:</el-checkbox>
            <el-input v-model="item.title"
                      style="width:240px"></el-input>
            <!-- 图片上传 -->
            <el-upload action="#"
                       list-type="picture-card"
                       :http-request="handleUpload"
                       :on-remove="handleRemove"
                       multiple>
              <i class="el-icon-plus"></i>
            </el-upload>

          </div>
          <!-- 添加按钮 -->
          <el-button type="danger"
                     :disabled="qsForm.questionType!=='2'"
                     @click="add"
                     size="small">+增加选项与答案</el-button>
        </el-form-item>
        <!-- 解析视频 输入框-->
        <el-form-item label="解析视频:">
          <el-input v-model="qsForm.videoURL"
                    style="width:400px"></el-input>
        </el-form-item>
        <!-- 答案解析  富文本 -->
        <el-form-item label="答案解析:"
                      prop="question">
          <quill-editor v-model="qsForm.answer"
                        :options="editorOptions"></quill-editor>
        </el-form-item>
        <!-- 题目备注 文本域-->
        <el-form-item label="题目备注:">
          <el-input type="textarea"
                    :rows="4"
                    v-model="qsForm.remarks"
                    style="width:400px"></el-input>
        </el-form-item>
        <!-- 试题标签 输入框-->
        <el-form-item label="试题标签:">
          <el-select style="width:400px"
                     v-model="qsForm.tags"
                     multiple
                     filterable
                     allow-create
                     default-first-option
                     placeholder="请选择试题标签">
            <el-option v-for="item in tagsOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 提交按钮-->
        <el-form-item>
          <el-button v-if="!$route.query.id"
                     @click="submit()"
                     type="primary">确认提交</el-button>
          <el-button v-else
                     @click="update()"
                     type="success">确认修改</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<script>
import { simple as getALLSubject } from '@/api/hmmm/subjects'
import { simple as getCatalog } from '@/api/hmmm/directorys'
import { simple as getTag } from '@/api/hmmm/tags'
import { list as getCompany } from '@/api/hmmm/companys'
import { provinces as getCity, citys as getArea } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { add, detail, update } from '@/api/hmmm/questions'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { getToken } from '@/utils/auth'

import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKIDmQr55tYzStKk1Jbr4GRadbS8bptjTzHK',
  SecretKey: 'qW7Yt2yeLxbIvNdjcFdleQ4VgcXM7oV6'
})
export default {
  components: {
    quillEditor
  },
  data () {
    return {

      // 获取token
      token: getToken(),
      // 富文本
      editorOptions: {
        content: '',
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      // 试题对象
      qsForm: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: null, // 地区
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: null, // 题干
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },
      subjectOptions: [], // 学科选项
      catalogOptions: [], // 目录选项
      enterpriseOptions: [], // 企业选项
      cityOptions: getCity(), // 城市选项
      areaOptions: [], // 地区选项
      directionOptions: direction, // 方向选项
      tagsOptions: [], // 标签选项
      questionType, // 题型
      difficulty, // 难度
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.getALLSubject()
    this.getCompany()
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  watch: {
    '$route.query': function () {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.qsForm = {
          subjectID: null,
          catalogID: null,
          enterpriseID: null,
          province: null,
          city: null,
          direction: null,
          questionType: '1',
          difficulty: '1',
          question: null,
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  methods: {
    // 获取题目信息
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.qsForm = data
      const res = await getCatalog({ subjectID: this.qsForm.subjectID })
      this.catalogOptions = res.data
      const res2 = await getTag({ subjectID: this.qsForm.subjectID })
      this.tagsOptions = res2.data
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 改变学科
    async changeSubject (subject) {
      this.qsForm.catalogID = null
      const res = await getCatalog({ subjectID: this.qsForm.subjectID })
      this.catalogOptions = res.data
      this.qsForm.tags = null
      const res2 = await getTag({ subjectID: this.qsForm.subjectID })
      this.tagsOptions = res2.data
    },
    // 提交
    submit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.qsForm }
          data.tags = data.tags.join('')
          await add(data)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 修改
    update () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.qsForm }
          data.tags = data.tags.join('')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    /* 上传图片 */
    handleUpload ({ file }) {
      // 上传配置对象 这个对象中有一个.file属性就是上传的文件对象
      console.log(file)
      // 收集到上传的文件对象, 传递到腾讯云服务器上
      cos.putObject(
        {
          Bucket: 'hrsaas92-1309363254' /* 必须 */,
          Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
          Key: +new Date() + file.name /* 必须,上传的文件的名字 */,
          StorageClass: 'STANDARD',
          Body: file, // 上传文件对象
          // 上传期间触发的函数, 受网络影响多次触发
          onProgress: (progressData) => {
            // 将函数改成箭头函数, 后期会处理到data中的数据
            // progressData 是一个对象 loaded已上传 total总文件大小 speed上传的速度 percent 上传的进度
            console.log(JSON.stringify(progressData))
            // console.log(this)
          }
          // 上传完成后的处理函数 有可能会成功 有可能会失败
        },
        (err, data) => {
          // 将函数改成箭头函数, 后期会处理到data中的数据
          // 上传成功后会打印data ,上传失败会得到err对象
          // console.log(err || data)
          if (err) return this.$message.error('上传失败,请稍后重试')
          // 上传完成 得到data data中有一个 Location 字段 就是腾讯云存储的图像地址
          console.log(data.Location)
          // 将腾讯云返回的地址存储到数据库中
        }
      )
    },
    // 删除图片
    handleRemove (file, fileList) {
      // console.log(file, fileList)
    },
    // 增加选项
    add () {
      // 规律：
      // 索引 0 ---> A  ascii  65
      // 索引 1 ---> B  ascii  66
      // 索引 2 ---> C  ascii  67
      // 索引 3 ---> D  ascii  68
      // 索引 4 ---> E  ascii  69
      // ...
      // 总结 code = String.fromCharCode(index + 65)
      this.qsForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.qsForm.options.length),
        title: '',
        img: ''
      })
    },

    // 选择单选框
    changeRadio (item) {
      // 1. 清除所有的选中
      this.qsForm.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },
    // 校验题干
    checkQustion () {
      // 调用el-form组件的 validateField 校验  question  字段
      this.$refs.form.validateField('question')
    },
    // 获取学科最新数据
    async getALLSubject () {
      const res = await getALLSubject()
      this.subjectOptions = res.data
    },
    async getCompany () {
      const res = await getCompany({ pagesize: 10000 })
      // res.data.items 下拉选项数据  id 选项值  company 选项文字
      this.enterpriseOptions = res.data.items
    },
    // 获取城市下拉
    getArea (cityName) {
      // 清空  地区选中的值
      this.qsForm.city = null
      // cityName 是你选中城市后的值
      this.areaOptions = getArea(cityName)
    }
  }
}
</script>

<style scoped lang='less'>
.question-new {
  padding: 0 20px;
  ::v-deep .ql-editor {
    height: 200px;
  }
}
.question-new .option_item div {
  display: inline-block;
  margin-left: 20px;
  margin-bottom: 20px;
}
</style>
